<?php
class SiteController extends FrontController{
	function SiteController(){
		parent::FrontController();
	}
	
// 	function region(){
// 		$mod = new RegionModel();
// 		$rs = $mod->find();
		
// 		foreach ($rs as $r){
// 			echo "INSERT INTO region (id,name,parent,path_id,path_name)values ({$r['_id']}, '{$r['name']}', '{$r['parent']}', '{$r['path_id']}', '{$r['path_name']}');<br>\n";
// 		}
// 		exit;
// 	}
	
	function test(){
// 		$page_mod = new PageModel();
// 		$page = $page_mod->get_by_attrs(array('name'=>'site_index', 'available'=>true));
// 		$tree = new PageTree($page['_id']);
// 		echo $tree->gen_template();

// 		$form = new FormHelper(array(
// 			'name' => 'article_cate',
// 		));
		$this->display();	
	}
	
	function index(){
		//如果有扉页，则直接进入扉页
		if(REDIRECT_URL=='' || REDIRECT_URL == '/'){
			$index_file = ROOT_PATH . '/sites/main/' . MAIN_DOMAIN . '/templates/default.htm';
			if(is_file($index_file)){
				$this->display('default');
				return;
			}
		}
		$this->assign('name','ycoe');
		if(isset($_REQUEST['tpl'])){
			$this->display(trim($_REQUEST['tpl']));
		}else{
			$this->display();
		}
	}
	
	public function logout(){
		remove_session('user');
		$this->redirect('/');
	}
	
	public function regist(){
		$return_url = '/';
		if(isset($_REQUEST['return_url'])){
			$return_url = $_REQUEST['return_url'];
		}
		$user = get_session('user');
		if(!empty($user) && $user['authority'] === true){
			//已经登录
			$this->redirect($return_url);
		}
		$this->assign('return_url', $return_url);
		if(IS_POST){
			$password = trim($_POST['password']);
			$email = trim($_POST['email']);
			$user_name = self::get_post_val('user_name', preg_replace('/(.*)@.*/i', '$1', $email));
			$user = array(
				'user_name' => $user_name,
				'site_id' => SITE_ID,
				'password' => $password,
				'email' => $email,
			);
			$result = UCenter::add_user($user);
			if($result['result'] === true){
				//注册成功，帮其登录
				$result = $this->do_login($user);
				if($result['result'] === true){
					$this->redirect($return_url);
					exit;
				}else{
					//如果自动登录失败，则转向登录页面
					$this->redirect('/login.html?return_url=' . $return_url);
				}
			}else{
				//注册失败
				$this->assign('error', $result['info']);
				$this->assign('user', $user);
			}
		}
		$this->page_title = '用户注册 - ' . $this->site_info['name'];
		$this->display();
	}
	
	private function on_login($user){
		//记录Session
		if(isset($user['password'])){
			unset($user['password']);
		}
		$user['authority'] = true;
		set_session('user', $user);
	}
	
	private function do_login($user){
		if(strlen($user['password'])<5){
			return array('result' => false, 'info' => '密码错误！');
		}
		
		$result = UCenter::login(SITE_ID, $user['user_name'], $user['password']);
		if($result['result'] === true){
			$this->on_login($result['data']);
		}
		return $result;
	}
	
	/**
	 * 用户登录
	 */
	public function login(){
		$return_url = '/';
		if(isset($_REQUEST['return_url'])){
			$return_url = $_REQUEST['return_url'];
		}
		if(empty($return_url)){
			$return_url = '/';
		}
		$user = get_session('user');
		if(!empty($user) && $user['authority'] === true){
			//已经登录
			$this->redirect($return_url);
		}
		$this->assign('return_url', $return_url);
		if(IS_POST){
			//登录操作
			$user_name = trim($_POST['user_name']);
			$password = trim($_POST['password']);
			$user = array(
				'user_name' => $user_name,
				'password' => $password,
				'site_id' => SITE_ID,
			);
			$result = $this->do_login($user);
			if($result['result'] === true){
				$this->redirect($return_url);
				exit;
			}else{
				//如果登录失败，则转向登录页面
				$this->assign('user', $user);
				$this->assign('error', $result['info']);
			}
		}
		//显示登录界面
		$this->page_title = '用户登录 - ' . $this->site_info['name'];
		$this->display();
	}
	
	/**
	 * 为高级编辑器编写的上传文件方法
	 */
	public function upload(){
		$base_path = 'sites/main/' . MAIN_DOMAIN . '/file/' . date("Y_m") . '/';
		$result = upload_img($base_path, 'imgFile');
		header('Content-type: text/html; charset=UTF-8');
		if($result['result'] === false){
			//错误
			echo json_encode(array('error' => 1, 'message' => $result['info']));
		}else{
			//成功
			echo json_encode(array('error' => 0, 'url' => $result['data'], 'path' => $result['path']));
		}
	}
	
	public function file_manager(){
		$path = self::get_val('path'); //分类
		$order = self::get_val('order');
		$dir = self::get_val('dir'); //类型：image
		$file = new FileModel();
		$condition = array('site_id'=>SITE_ID, 'type'=>FileModel::get_type_by_name($dir));
		if(!empty($path)){
			//指定了分类
			$condition['cate'] = trim($path);
		}
		$files = $file->find($condition);
		$file_list = array();
		foreach($files as $file){
			$file_list[] = array(
				'is_dir' => false,
				'has_file' => false,
				'filesize' => $file['size'],
				'dir_path' => '',
				'is_photo' => $dir === 'image',
				'filetype' => $file['postfix'],
				'url' => get_thumb_path($file['path'], '80x80'),
				'path' => $file['path'],
			);
		}
		usort($file_list, 'cmp_func');
		$result = array(
			'moveup_dir_path' => '/',	//相对于根目录的上一级目录
			'current_dir_path' => '/',	//相对于根目录的当前目录
			'current_url' => '/',		//当前目录的URL
			'total_count' => count($file_list),		//文件数
			'file_list' => $file_list,			//文件列表数组
		);
		echo json_encode($result);
	}
}

//排序
function cmp_func($a, $b) {
	global $order;
	if ($a['is_dir'] && !$b['is_dir']) {
		return -1;
	} else if (!$a['is_dir'] && $b['is_dir']) {
		return 1;
	} else {
		if ($order == 'size') {
			if ($a['filesize'] > $b['filesize']) {
				return 1;
			} else if ($a['filesize'] < $b['filesize']) {
				return -1;
			} else {
				return 0;
			}
		} else if ($order == 'type') {
			return strcmp($a['filetype'], $b['filetype']);
		} else {
			return strcmp($a['filename'], $b['filename']);
		}
	}
}